﻿using Coldairarrow.Entity.Base;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Util;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Base
{
    public partial class Base_UserDepartmentBusiness : BaseBusiness<Base_UserDepartment>, IBase_UserDepartmentBusiness, ITransientDependency
    {
        readonly Cache.IBase_UserCache _userCache;
        readonly IServiceProvider _serviceProvider;
        public Base_UserDepartmentBusiness(
            IDbAccessor db,
            Cache.IBase_UserCache userCache,
            IServiceProvider serviceProvider)
            : base(db)
        {
            _serviceProvider = serviceProvider;
            _userCache = userCache;
        }

        #region 外部接口

        public async Task<PageResult<Basr_UserDeptDTO>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            var search = input.Search;
            Expression<Func<Base_UserDepartment, Base_Department, Basr_UserDeptDTO>> select = (a, b) => new Basr_UserDeptDTO
            {
                DepartmentName = b.Name

            };
          select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<Base_Department>() on a.DepartmentID equals b.Id into ab
                    from b in ab.DefaultIfEmpty()

                    select @select.Invoke(a, b);
            if (!search.Keyword.IsNullOrEmpty())
            {
                var keyword = $"%{search.Keyword}%";
                q = q.Where(x =>
                      EF.Functions.Like(x.DepartmentName, keyword));
            }
        
           
            return await q.GetPageResultAsync(input);
        }

        public async Task<Base_UserDepartment> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        public async Task AddDataAsync(List<Base_UserDepartment> data)
        {
            await InsertAsync(data);
        }

       
        public async Task UpdateCacheAsync(Base_UserDepartmentDTO data)
        {
            var userSvc = _serviceProvider.GetRequiredService<Base_Manage.IBase_UserBusiness>();
            var user = await userSvc.GetTheDataAsync(data.UserID);
            user.DeptIds = data.DepartmentID;
            await _userCache.UpdateCacheAsync(data.UserID, user);
        }

        public async Task UpdateDataAsync(Base_UserDepartment data)
        {
            await UpdateAsync(data);
        }

        public async Task DeleteDataAsync(List<string> ids)
        {
            var model = await GetTheDataAsync(ids[0]);
            await DeleteAsync(ids);
            var userSvc = _serviceProvider.GetRequiredService<Base_Manage.IBase_UserBusiness>();
            var user = await userSvc.GetTheDataAsync(model.UserID);
            for (int i = 0; i < ids.Count; i++)
            {
                user.DeptIds.Remove(ids[i]);
            }
            await _userCache.UpdateCacheAsync(model.UserID, user);
        }

        public async Task DeleteOtherIdDataAsync(object where)
        {
            await DeleteOtherIdAsync(where);
        }

        /// <summary>
        /// 通过 用户id主键 查找组织
        /// </summary>
        /// <param name="UserId"></param>
        /// <returns></returns>
        public async Task<List<Basr_UserDeptDTO>> GetDataListByAsync(string UserId)
        {
            Expression<Func<Base_UserDepartment, Base_User, Base_Department, Basr_UserDeptDTO>> select = (a, b, c) => new Basr_UserDeptDTO
            {
                DepartmentName = c.Name,
                     
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<Base_User>() on a.UserID equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<Base_Department>() on a.DepartmentID equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    select @select.Invoke(a, b, c);
            //筛选
            if (!UserId.IsNullOrEmpty())
            {
                q = q.Where(w => w.UserID == UserId);
            }
            var res = await q.ToListAsync();

            return res;
        }

        /// <summary>
        /// 根据部门编号查询下面的用户
        /// </summary>
        /// <param name="Deptid"></param>
        /// <returns></returns>
        public async Task<List<Basr_UserDeptDTO>> GetDataListByAsyncDeptid(string Deptid)
        {
            Expression<Func<Base_UserDepartment, Base_User, Base_Department, Basr_UserDeptDTO>> select = (a, b, c) => new Basr_UserDeptDTO
            {
                DepartmentName = c.Name,
                RealName=b.RealName,
                HeadImg=b.HeadImg,
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<Base_User>() on a.UserID equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<Base_Department>() on a.DepartmentID equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    select @select.Invoke(a, b, c);
            //筛选
            if (!Deptid.IsNullOrEmpty())
            {
                q = q.Where(w => w.DepartmentID == Deptid);
            }
            var res = await q.ToListAsync();

            return res;
        }







        #endregion

        #region 私有成员

        #endregion
    }
}